package com.edu.lxshpc.utils;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTHeader;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.edu.lxshpc.pojo.User;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author zgh
 * @date 2023/10/26
 */
@Slf4j
public class Utils {
    private static final String PHONE_NUMBER_REGEX = "^1[3-9]\\d{9}$";
    private static  final  String Token_Header = "Bearer";
    private static final String Token_key = "20231120lxsh";
    /**
     * @param phoneNumber 手机号
     * @return 成功或失败
     */
    public static boolean validate(String phoneNumber) {
        if ("".equals(phoneNumber) || phoneNumber == null) {
            return false;
        }
        Pattern pattern = Pattern.compile(PHONE_NUMBER_REGEX);
        return pattern.matcher(phoneNumber).matches();
    }

    /**
     * 利用hutool生成token
     *
     * @param user 用户信息数
     * @return 返回token
     */
    public static String createToken(User user) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime nowAfter = now.plusDays(14);
        Map<String, Object> payload = new HashMap<>();
        //签发时间
        payload.put(JWTPayload.ISSUED_AT, now);
        //过期时间
        payload.put(JWTPayload.EXPIRES_AT, nowAfter);
        //生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);
        //载荷
        String s = JSONUtil.toJsonStr(user);
        payload.put("lxsh_user", s);
        payload.put("nowAfter",nowAfter.toString());
        return Token_Header +" "+ JWTUtil.createToken(payload,Token_key.getBytes());
    }

    /**
     * 验证token
     *
     * @param token 待验证的token
     * @param key   key
     * @return 返回验证结果
     */
    public static Boolean verificationToken(String token, String key) {
        // 返回token校验
        return JWTUtil.verify(token, key.getBytes());
    }

    /**
     * 解析·token
     *
     * @param token token
     * @return 返回用户信息
     */
    public static User parseToken(String token) {
        if (token == null || "".equals(token)) {
            throw new MyException("token为空");
        }
        token = token.split(" ")[1];
        // token校验是否合法
        boolean validate = verificationToken(token,Token_key);
        if (!validate) {
            throw new MyException("token无效,重新登录");
        }
        // token是否过期
        final JWT jwt = JWTUtil.parseToken(token);
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;

        LocalDateTime dateTime = LocalDateTime.parse(jwt.getPayload("nowAfter").toString(), formatter);
        boolean before = LocalDateTimeUtil.now().isBefore(dateTime);
        if (!before) {
            throw new MyException("token已过期,重新登录");
        }
        jwt.getHeader(JWTHeader.TYPE);
        String userJson = jwt.getPayload("lxsh_user").toString();
        return JSONUtil.toBean(userJson, User.class);
    }


}
